package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import com.atguigu.lease.model.enums.ItemType;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {

        return new Converter<String, T>() {
            @Override
            public T convert(String source) {

                //ItemType.values()  获取ItemType这个枚举中所有的选项值
                // targetType.getEnumConstants() 已知枚举的Class，获取某个枚举中的所有选项值
                return Arrays.stream(targetType.getEnumConstants()).filter(item->item.getCode()==Integer.parseInt(source))
                        .findFirst()
                        .orElseThrow(IllegalArgumentException::new);
            }
        };
    }
}
